/**
 * Adapter danh sach cac bai hat Online
 */
package com.toidep.adapters;

import java.util.ArrayList;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseFragment;
import com.toidep.config.ConfigUtility;
import com.toidep.entities.CommentEntity;
import com.toidep.interfaces.ResponseListener;
import com.toidep.widgets.sectionlist.AmazingAdapter;

public class CommentAdapter extends AmazingAdapter{
	
	private BaseFragment parentFragment;
	
	private ArrayList<CommentEntity> listComment;
	public ArrayList<ViewHolder> arrViewHolder;			// QUan ly cac ViewHolder

	private int adapterTypeByScreen;					// Adapter nay cua Screen nao de goi API tuong ung cho dung
	private int typeComment;							// typeComment = 1: Model | 2: Album | 3: Video
	private String parent_id;
	
	/**
	 * Constructor 
	 * Khoi tao Adapter lay danh sach Comment
	 * @param ff
	 * @param adapterTypeByScreen
	 * @param typeComment = 1: Model | 2: Album | 3: Video 
	 * @param parent_id
	 */
	public CommentAdapter(BaseFragment ff, int adapterTypeByScreen, int typeComment, String parent_id) {
		this.parentFragment = ff;
		this.listComment = new ArrayList<CommentEntity>();
		this.arrViewHolder = new ArrayList<ViewHolder>();

		this.adapterTypeByScreen = adapterTypeByScreen;
		this.typeComment = typeComment;
		this.parent_id = parent_id;
	}
	
	public void setParentId(String parent_id) {
		this.parent_id = parent_id;
	}
	
	public ArrayList<CommentEntity> getListAdapter() {
		return this.listComment;
	}
	
	public void resetList(ArrayList<CommentEntity> l) {
		if (listComment == null) {
			listComment = new ArrayList<CommentEntity>();
		}
		//===== Tao Mang ViewHolder=====
		if (arrViewHolder == null) {
			arrViewHolder = new ArrayList<ViewHolder>();
		}
		arrViewHolder.clear();
		for (int i = 0; i < l.size(); i++) {
			arrViewHolder.add(null);
		}
		//==============================
		listComment.clear();
		listComment.addAll(l);
		notifyDataSetChanged();
	}
	
	public void resetList() {
		if (listComment == null) {
			listComment = new ArrayList<CommentEntity>();
		}
		if (arrViewHolder == null) {
			arrViewHolder = new ArrayList<ViewHolder>();
		}
		listComment.clear();
		
		getFirstPage();
	}
	
	public int getCount() {
		if (listComment != null)
			return listComment.size();
		else 
			return 0;
	}

	public CommentEntity getItem(int position) {
		return listComment.get(position);
	}

	public long getItemId(int position) {
		return position;
	}
	
	public void onItemClick(int position) {
		if (getCount() == 0) return;
//		try {
//			mainActivity.mainFragment.openFragmentScreen(Constants.CATEGORY_MODEL_DETAL, null);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
	}
	
	// TODO: onNextPageRequested
	@Override
	protected void onNextPageRequested(int page) {
		getCommentsNormal(page);
	}

	@Override
	protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
		// do nothing
	}
	
	private class ViewHolder {
		public TextView username, time_after, comment;
	}

	@Override
	public View getAmazingView(int position, View convertView, ViewGroup parent) {
		final ViewHolder viewHolder;
		if (convertView == null) {
			
			convertView = parentFragment.getActivity().getLayoutInflater().inflate(R.layout.layout_itemlist_comment, null);
			viewHolder = new ViewHolder();
			viewHolder.username = (TextView) convertView.findViewById(R.id.username);
			viewHolder.time_after = (TextView) convertView.findViewById(R.id.time_after);
			viewHolder.comment = (TextView) convertView.findViewById(R.id.comment);
			
			convertView.setTag(viewHolder);
			
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		
		final CommentEntity currentModel = getItem(position);
		
		viewHolder.username.setText(currentModel.getUsername());
		viewHolder.time_after.setText(currentModel.getTime_after());
		viewHolder.comment.setText(currentModel.getComment());
		
		return convertView;
	}

	@Override
	public void configurePinnedHeader(View header, int position, int alpha) {
		
	}

	@Override
	public int getPositionForSection(int section) {
		return 0;
	}

	@Override
	public int getSectionForPosition(int position) {
		return 0;
	}

	@Override
	public int getSectionPosition(int position) {
		return 0;
	}

	@Override
	public Object[] getSections() {
		return null;
	}
	
	/**
	 * Clear Adapter ve null
	 */
	public void clear() {
		resetPage();
		listComment.clear();
		clearTemporarity();
		notifyDataSetChanged();
	}
	
	/**
	 * Xoa cac bien su dung: ViewHolder...
	 */
	public void clearTemporarity() {
		if (arrViewHolder != null)
			arrViewHolder.clear();
//		arrViewHolder = null;
	}
	
	/**
	 * Clear memory cache
	 */
	public void clearMemoryCacheOnly() {
		Log.e("SongsAdapter", "clearMemoryCacheOnly");
//		imageFetcher.clearMemoryCacheOnly();
	}
	
	/**
	 * Goi ham nay khi Fragment chua no xay ra onDestroy
	 */
	public void destroyAdapter() {
		clear();
		listComment = null;
		arrViewHolder = null;
//		imageFetcher = null;
	}
	
	// ======================== GOI API TUONG UNG VOI CAC ADAPTER ==========================
	
	/**
	 * List trong muc Home -> Models
	 * Lay danh sach nguoi mau theo categories NEW - HOT - TOP - ALL
	 */
	private void requestAPI(int page, ResponseListener responseListener) {
		ApiController.getComments(parentFragment.getActivity(), typeComment, parent_id,
				page, ConfigUtility.PAGE_SIZE, responseListener);
	}
	
	private void getCommentsNormal(final int page) {
		
		ResponseListener responseListener = new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				notifyNoMorePages();
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null) {
					try {
						ArrayList<CommentEntity> list = ParseJSON.getAllCommentsFromResponse(response);
						if (list != null && list.isEmpty() == false) {
							listComment.addAll(list);
							//===== Tao Mang ViewHolder=====
							for (int i = 0; i < list.size(); i++) {
								arrViewHolder.add(null);
							}
							//==============================
							nextPage();
							notifyDataSetChanged();
							if (list.size() < ConfigUtility.PAGE_SIZE)
								notifyNoMorePages();
							else
								notifyMayHaveMorePages();
						} else {
							notifyNoMorePages();
						}
					} catch (Exception e) {
						notifyNoMorePages();
					} finally {
						isLoadingMore = false;
					}
				} else {
					notifyNoMorePages();
				}
				
			}
		};

		requestAPI(page, responseListener);
	}
	
	private void getFirstPage() {
		int page = 1;
		ResponseListener responseListener = new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				notifyNoMorePages();
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null) {
					ArrayList<CommentEntity> list = ParseJSON.getAllCommentsFromResponse(response);
					if (list != null && list.isEmpty() == false) {
						notifyMayHaveMorePages();
						
						resetList(list);
					} else {
						notifyNoMorePages();
					}
				} else {
					notifyNoMorePages();
				}
			}
		};

		requestAPI(page, responseListener);
	}

}
